<template>
  <a-modal
    v-model:visible="preview"
    :title="title"
    :footer="null"
    width="80%"
    :maskClosable="true"
  >
    <div class="head">
      <div class="drag-bar" v-if="Data"></div>
      <div class="head-flex">
        <div class="time">已录制:{{ formattedTime }}</div>
        <div v-if="allTime">|</div>
        <div class="time" v-if="allTime">总时长:{{ allTime }}</div>
        <a-button
          v-if="allTime == ''"
          type="primary"
          @click="startRecord"
          class="start"
          size="small"
          >开始录制</a-button
        >
        <a-button
          v-if="isEnd"
          type="primary"
          @click="stopRecord"
          danger
          class="end"
          size="small"
          >结束录制</a-button
        >

        <div class="head-btn">
          <!-- <div @click="$refs.setRef.show()" class="btn">
            <img src="../../../assets/icon/3.png" class="img1" alt="" srcset="" />
          </div> -->

          <!-- <div @click="minimizeWindow" class="btn">
              <img src="../../assets/icon/3.png" class="img1" alt="" srcset="" />
            </div> -->
          <div class="btn" @click="restore()" v-if="isMaximized">
            <img
              src="../../../assets/icon/5.png"
              class="img2"
              alt=""
              srcset=""
            />
          </div>
          <div class="btn" @click="restore()" v-else>
            <img
              src="../../../assets/icon/5.png"
              class="img1"
              alt=""
              srcset=""
            />
          </div>
          <!-- <div class="btn" @click="close">
            <img src="../../../assets/icon/6.png" class="img1" alt="" srcset="" />
          </div> -->
        </div>
      </div>
    </div>
    <div class="conten">
      <video id="video" controls width="600" height="400"></video>
      <a-spin
        v-if="isLoding"
        style="
          position: fixed;
          left: 50%;
          top: 50%;
          transform: translateX(-50) translateY(-50%);
        "
        size="80"
      />
    </div>

    <a-modal
      v-model:visible="notStarted"
      title="温馨提示"
      width="50%"
      :footer="null"
      :maskClosable="true"
    >
      <div class="started">
        <div>请点击【开始录制】进行录制</div>
        <div v-if="countdown != 0">倒计时：{{ formattedTime1 }}</div>
      </div>
    </a-modal>

    <a-modal
      v-model:visible="prompt"
      title="温馨提示"
      width="50%"
      @ok="handleOk"
      :maskClosable="true"
    >
      <div>确定要停止录制？</div>
    </a-modal>
  </a-modal>
</template>
<script>
import { ipcApiRoute, specialIpcRoute } from "@/utils/ipcMainApi";
import {
  getCourseListDetil,
  uploadRecordingStatus,
  getClientComment,
} from "@/api/course.js";
import { uploadVideo } from "@/api/file.js";

import "../../../utils/hls";

import { ipc } from "@/utils/ipcRenderer";
import Player from "xgplayer";
import { toRaw } from "vue";
//引入fs模块
const fs = require("fs");
import { createStream, createRecorder } from "electron-webrtc";
import { saveAs } from "file-saver"; // 用于保存文件
// import MediaRecorder from "node-media-recorder";

// import Set from "../../components/set.vue";
import axios from "axios";

export default {
  components: {
    // Set,
  },
  data() {
    return {
      stream: null, // 视频流对象
      recorder: null, // 录像对象
      recordedTime: "",
      isMaximized: true,
      businessId: null,
      isEnd: false,
      time: 0, // 存储时间（以秒为单位）
      allTime: "",
      vidoUrl: "",
      type: null,
      Data: null,
      blob: null,
      isOver: false,
      recordingStatus: null,
      isLoding: false,
      formState: {},
      rtspUrl: "",
      preview: false,
      prompt: false,
      title: "",
      notStarted: false,
      countdown: 0, // 倒计时
      countdownTime: null,
    };
  },
  created() {},
  mounted() {
    // this.init();
    // this.requestCameraAccess();
    // this.startCamera();
    // const hash = window.location.hash;
    // const params = new URLSearchParams(hash.split("?")[1]);
    // this.businessId = params.get("id");
    // this.type = params.get("type");
    // this.type == 1 ? this.getClientGrindingData() : this.getlistClientComment();
    // this.takePhotoUpload();
    // this.began();
  },
  watch: {
    // 监听message属性的变化
    time(newValue, oldValue) {
      console.log("message变化了", newValue, oldValue);
      if (newValue == 600) {
        this.$message.warning("录制成功后，自动上传视频！");
      }
    },
  },
  computed: {
    formattedTime() {
      const hours = Math.floor(this.time / 3600);
      const minutes = Math.floor((this.time % 3600) / 60);
      const seconds = this.time % 60;
      return `${minutes < 10 ? "0" + minutes : minutes}:${
        seconds < 10 ? "0" + seconds : seconds
      }`;
    },
    formattedTime1() {
      const hours = Math.floor(this.countdown / 3600);
      const minutes = Math.floor((this.countdown % 3600) / 60);
      const seconds = this.countdown % 60;
      return `${minutes < 10 ? "0" + minutes : minutes}:${
        seconds < 10 ? "0" + seconds : seconds
      }`;
    },
  },
  methods: {
    //recordingStatus  录制状态（0未开始，1录制中，2录制成功，3录制失败）
    show(type, item) {
      console.log(item, "item");

      this.formState = this.getStat();
      //   const hash = window.location.hash;
      //   const params = new URLSearchParams(hash.split("?")[1]);
      //   this.businessId = params.get("id");
      //   this.type = params.get("type");
      this.preview = true;

      this.businessId = item.id;
      this.type = type;
      this.type == 1
        ? this.getClientGrindingData()
        : this.getlistClientComment();
      this.startRecording();
      this.time = 0;
      this.allTime = "";
      if (item.recordingStatus == 0) {
        this.isEnd = false;
      }

      if (item.recordingStatus == 1) {
        this.isEnd = true;
        this.allTime = null;
      }

      this.endTimer();

      this.began();

      if (this.countdownTime) {
        clearInterval(this.countdownTime); // 清除计时器以避免内存泄漏
      }
    },

    // 获取状态
    getStat() {
      if (localStorage.getItem("set")) {
        return JSON.parse(localStorage.getItem("set"));
      }
    },
    //   recordingMethod  录制方式（0自动录制，1手动录制）
    async getClientGrindingData() {
      //获取磨课
      const res = await getCourseListDetil({ id: this.businessId });
      this.Data = res.data;
      this.title = "磨课录制-" + res.data.name;
      // 未开始
      if (res.data.recordingStatus == 0) {
        this.notStarted = true;
        if (res.data.recordingMethod == 0) {
          console.log("倒计时");
          // startTime - 当前时间
          let timestamp = new Date();
          let date = new Date(res.data.startTime);
          // let date = new Date("2025-07-17 15:00:00");

          this.countdown = 0;
          if (date > timestamp) {
            let timeDifferenceInSeconds = date.getTime() - timestamp.getTime();
            this.countdown = Math.floor(timeDifferenceInSeconds / 1000);

            this.countdownTime = setInterval(() => {
              this.countdown--; // 每秒时间增加1
            }, 1000);
          } else {
            this.countdown = 0;
          }
        }
      } else {
        // 进行中
      }
    },
    async getlistClientComment() {
      //获取评课
      const res = await getClientComment({ id: this.businessId });
      this.Data = res.data;
      this.title = "评课录制-" + res.data.name;
      // 未开始
      if (res.data.recordingStatus == 0) {
        this.notStarted = true;
        // 自动录制
        if (res.data.recordingMethod == 0) {
          // startTime - 当前时间
          let timestamp = new Date();
          let date = new Date(res.data.startTime);
          // let date = new Date("2025-07-17 15:00:00");

          this.countdown = 0;
          if (date > timestamp) {
            let timeDifferenceInSeconds = date.getTime() - timestamp.getTime();
            this.countdown = Math.floor(timeDifferenceInSeconds / 1000);

            this.countdownTime = setInterval(() => {
              this.countdown--; // 每秒时间增加1
            }, 1000);
          } else {
            this.countdown = 0;
          }
        }
      } else {
        // 进行中
      }
    },
    // 开始
    began() {
      const video = document.getElementById("video");

      //播放录制的视频
      if (Hls.isSupported()) {
        // let url =
        //   "http://" +
        //   this.formState.network +
        //   ":" +
        //   this.formState.port +
        //   "/stream/play/hlsStream.m3u8";
        this.rtspUrl = this.formState.network + this.formState.port;

        let url = `http://192.168.1.117:8080/stream/play/${this.businessId}/hlsStream.m3u8`;
        const hls = new Hls();
        hls.loadSource(url);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          // 直接跳转到末尾（最新时刻）
          video.currentTime = video.duration;
        });
      } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
        video.src = url;
        video.addEventListener("loadedmetadata", () => video.play());
      }
    },
    save() {
      const formData = new FormData();
      formData.append("macAddress", localStorage.getItem("macAddress"));
      formData.append("businessId", this.businessId);
      formData.append("businessType", 1);
      formData.append("fileType", 1);
      formData.append("videoLength", this.time);
      formData.append("videoFile", this.blob, "recorded.mp4");
      this.uploadVideo(formData);
      console.log(this.blob, "视频文件");
    },
    async uploadVideo(formData) {
      this.isLoding = true;
      const res = await uploadVideo(formData);
      this.isLoding = false;
      this.recordingStatus = 4;
      this.updataStatus();
      alert("保存成功");
      console.log(res, "上传结果");
    },
    async updataStatus() {
      const res = await uploadRecordingStatus({
        macAddress: localStorage.getItem("macAddress"),
        businessId: this.businessId,
        businessType: this.type,
        recordingStatus: this.recordingStatus,
      });
      console.log(res, "更新状态");
    },

    async takePhotoUpload() {
      console.log("===========进入摄像头函数");
      let device = ""; // 所选择的摄像头 deviceId
      // 加入音频（ 直接 audio: true, video: true 无效 所以要单独写 而后再另外加入音频）
      let audioTracks = await navigator.mediaDevices
        .getUserMedia({ audio: true, video: false })
        .then((mediaStream) => mediaStream.getAudioTracks()[0]);
      // 此处开启摄像头
      let stream = navigator.mediaDevices
        .enumerateDevices()
        .then((devices) => {
          //多个摄像头设备时，该处根据设备id判断具体使用哪个摄像头设备
          for (let i in devices) {
            if (devices[i].kind == "videoinput") {
              device = devices[i];
              break;
            }
          }
        })
        .then(async () => {
          navigator.mediaDevices
            .getUserMedia({
              audio: false,
              video: {
                sourceId: device.deviceId, // 把对应的 摄像头ID 放到这里
                // width: 500,
                height: 600, // 宽高可根据个人不同设计
                //如果拍照不清晰，考虑加入以下参数，但考虑下摄像头的高度和画布的高度
                width: { min: 1000, ideal: 1000, max: 3264 },
                // height:{min: 1080, ideal: 1080, max: 2488}
              },
            })
            .then(async (success) => {
              this.startType = 0;
              sessionStorage.setItem("startType", this.startType);
              success.addTrack(audioTracks); //加入音频
              this.$refs["videoElement"].srcObject = success; //测试阶段通过播放来判断是否成功调取成功
              this.$refs["videoElement"].play();
              //   this.createRecorder(success);
              this.stream = success;
              return;
            });

          // .catch((error) => {
          //   console.error("摄像头开启失败，请检查摄像头是否可用！");
          // });
        });
    },

    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        });

        this.$refs.videoElement.srcObject = stream;
      } catch (error) {
        console.error("Error accessing the camera", error);
      }
    },
    async requestCameraAccess() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        }); // 请求视频流
        const videoElement = document.getElementById("videoElement"); // 获取视频元素
        videoElement.srcObject = stream; // 将视频流绑定到视频元素上
        this.stream = stream;
        videoElement.play(); // 开始播放视频流
      } catch (error) {
        console.error("Error accessing the camera", error);
      }
    },
    restore() {
      ipc.invoke(ipcApiRoute.isMaximized).then((res) => {
        this.isMaximized = res;
        ipc.invoke(ipcApiRoute.restore).then((id) => {});
      });
    },
    close() {
      ipc.invoke(ipcApiRoute.close).then((id) => {});
    },
    minimizeWindow() {
      ipc.invoke(ipcApiRoute.minimize).then((id) => {});
    },

    startTimer() {
      this.timer = setInterval(() => {
        this.time++; // 每秒时间增加1
      }, 1000);
    },

    endTimer() {
      if (this.timer) {
        clearInterval(this.timer); // 清除计时器以避免内存泄漏
      }
    },
    // 开始播放
    async startRecording() {
      console.log("初始化录制==========");
      //   this.recordingStatus = 1;
      //   this.updataStatus();
      //   if (this.isEnd) {
      //     return;
      //   }

      try {
        const response = await axios.get(
          `http://192.168.1.117:8080/stream/startRstpConvert?rtspUrl=${this.rtspUrl}&fileName=${this.businessId}`
        ); // 替换为你的API URL
      } catch (error) {
        console.error("There was an error!", error);
      }

      // let recorder = new MediaRecorder(this.stream);
      // this.recorder = recorder;
      // recorder.start();
      //   this.startTimer();
      //   this.isEnd = true;
    },

    // 结束播放
    async stopRecording() {
      // let recorder = this.recorder;
      // recorder.stop();
      //   this.endTimer();
      //   this.isEnd = false;
      //   this.allTime = this.formattedTime;
      let that = this;

      try {
        const response = await axios.get(
          `http://192.168.1.117:8080/stream/stop?rtspUrl=${this.rtspUrl}&fileName=${this.businessId}`
        ); // 替换为你的API URL
      } catch (error) {
        console.error("There was an error!", error);
      }

      // recorder.ondataavailable = (event) => {
      //   let blob = new Blob([event.data], {
      //     type: "video/mp4",
      //   });
      //   // 将Blob转换为File
      //   const file = new File([blob], "测试", { type: "video/mp4" });
      //   console.log(file, "保存到本地");
      //   //调用你的接口上传
      //   // that.getSaveHzxx(file);
      //   // 保存录制的视频到本地
      //   that.saveMedia(blob);
      // };

      // recorder.onerror = (err) => {
      //   console.error(err, "这是一个错误");
      // };
    },

    // 开始播放
    async startRecord() {
      // let recorder = this.recorder;
      // recorder.stop();
      this.endTimer();
      this.isEnd = false;
      this.allTime = this.formattedTime;
      let that = this;

      try {
        const response = await axios.get(
          `http://192.168.1.117:8080/stream/startRecord?rtspUrl=${that.rtspUrl}&fileName=${that.businessId}`
        ); // 替换为你的API URL
      } catch (error) {
        console.error("There was an error!", error);
      }

      this.startTimer();
      this.isEnd = true;
    },
    // 确认结束
    stopRecord() {
      // let recorder = this.recorder;
      // recorder.stop();
      this.prompt = true;
    },
    // 结束播放
    async handleOk() {
      this.endTimer();
      this.isEnd = false;
      this.allTime = this.formattedTime;
      let that = this;

      try {
        const response = await axios.get(
          `http://192.168.1.117:8080/stream/stopRecord?rtspUrl=${that.rtspUrl}&fileName=${that.businessId}`
        ); // 替换为你的API URL
      } catch (error) {
        console.error("There was an error!", error);
      }
    },

    saveMedia(blob) {
      console.log("进入saveMedia函数--------");
      console.log(blob, "blob=====");
      let that = this;
      let reader = new FileReader();
      console.log(reader, "readerzhe jiushi d");
      reader.onload = () => {
        let buffer = new Buffer(reader.result);
        // 转换base64（不建议，视频过长数据量将过多）
        // var bitmap = new Buffer(buffer).toString('base64')
        let name = "test.mp4";

        // 保存到本地 名称自定义
        fs.writeFile(name, buffer, {}, (err, res) => {
          if (err) return console.error(err);
          this.isOver = true;
          this.recordingStatus = 4;
          this.updataStatus();
          that.blob = blob;
          that.stream.getTracks().forEach((track) => track.stop());
          console.log(blob);
          const url = URL.createObjectURL(blob);
          console.log(url, "地址");
          that.vidoUrl = url;
        });
      };
      reader.onerror = (err) => console.error(err, "reader=err");
      reader.readAsArrayBuffer(blob);
    },
  },
};
</script>
<style lang="less" scoped>
.drag-bar {
  width: 100%;
  -webkit-app-region: drag; //设置可以拖拽的区域
  text-align: left;
  font-weight: 500;
  font-size: 18px;
  color: #333333;
}

#video-player {
  width: 100%;
  height: calc(100% - 28px);
  background-color: #f0f2f5;

  .sunwinbox {
    padding: 20px;
  }

  .one-block-1 {
    font-size: 16px;
    padding-top: 10px;
  }

  .one-block-2 {
    padding-top: 10px;
  }
}

#videoElement {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.conten {
  width: 100%;
  height: calc(100% - 50px);
}

.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  background: #fff;
  color: #333333;
  margin-top: -20px;
}

.head-btn {
  display: flex;
}

.btn {
  width: 40px;
  height: 38px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.img1 {
  width: 18px;
}

.img2 {
  width: 18px;
}

.head-flex {
  display: flex;
  align-items: center;
}

.start {
  background: #237dff;
  color: #fff;

  margin-left: 10px;
  border-radius: 30px 30px 30px 30px;
}

.end {
  background: red;
  color: #fff;

  margin-left: 10px;
  border-radius: 30px 30px 30px 30px;
}

.end:hover {
  background: rgb(226, 104, 104);
  color: #fff;
}

.time {
  min-width: 100px;
  -webkit-app-region: drag; //设置可以拖拽的区域
}

#video {
  width: 100%;
  height: 400px;
  object-fit: fill;
}
.started {
  text-align: center;
  font-weight: 700;
  font-size: 20px;
  color: #237dff;
}
</style>
